package com.msb.strategy.util;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @Author: lmf
 * @Create: 2025/3/12 11:04
 * @module
 */
@Component
public class MobilOperatorUtil {
    @Resource
    private RestTemplate restTemplate;

    public final String SPACE = " ";
    public final String SEPARATE = ",";

    private final ObjectMapper objectMapper = new ObjectMapper();


    public String getMobileInfo(String mobile) {
        String url = "https://cx.shouji.360.cn/phonearea.php?number=";
        String CODE = "code";
        String DATA = "data";
        String CITY = "city";
        String PROVINCE = "province";
        String SP = "sp";


        // 发送请求
        String mobilInfoJson = restTemplate.getForObject(url + mobile, String.class);
        // 解析json
        Map map = null;
        try {
            map = objectMapper.readValue(mobilInfoJson, Map.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        Integer code = (Integer) map.get(CODE);
        Map<String, String> areaAndOperator = (Map<String, String>) map.get(DATA);
        if (code != 0 || StringUtils.isEmpty(areaAndOperator.get(CITY))) {
            return null;
        }


        // 封装返回参数
        String city = areaAndOperator.get(CITY);
        String province = areaAndOperator.get(PROVINCE);
        String operator = areaAndOperator.get(SP);
        return province + SPACE + city + SEPARATE + operator;
    }
}
